package com.carassistant.beta.phone;

import java.util.ArrayList;

import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.CallLog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.carassistant.beta.R;
import com.carassistant.beta.common.CarAssistantActivity;
import com.carassistant.beta.phone.adapter.RecentAdapter;

public class PhoneRecordActivity extends CarAssistantActivity implements OnItemClickListener{
	private ListView recentList; 
	private MyAsyncQueryHandler asyncQuery;
	public static final int TOKEN_ONCREATE = 0;
	public static final int TOKEN_UPDATE = 1;
	public static final int TOKEN_REFLESH = 54;
	private Handler handler;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.phone_record);
		
		initHandler();
		recentList = (ListView) findViewById(R.id.list_view); 
		recentList.setOnItemClickListener(this);
		
		asyncQuery = new MyAsyncQueryHandler(getContentResolver()); 
		getLogs(TOKEN_ONCREATE);
	}
	 
	/**
	 * 异步查询所有通话记录
	 * */
	private void getLogs(int token){ 
		asyncQuery.startQuery(token, null, CallLog.Calls.CONTENT_URI, 
				new String[]{CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME, CallLog.Calls.TYPE,CallLog.Calls.DATE},
				null, null, CallLog.Calls.DEFAULT_SORT_ORDER);
    }
	
	private void initHandler(){
		handler = new Handler(){
			public void handleMessage(android.os.Message msg) {
				getLogs(TOKEN_UPDATE);
			};
		};
	}
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		handler.sendEmptyMessageDelayed(0, 1000);
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		String number = (String) parent.getAdapter().getItem(position);
		dailNumber(number);
	} 
	
	/**
	 * 调用系统的拨号功能
	 * @param number
	 * */
	private void dailNumber(String number){
		if (number != null && !"".equals(number)) {
			Uri callUri = Uri.parse("tel:" + number);
			startActivity(new Intent(Intent.ACTION_CALL, callUri));
		} 
	}
	
	/**
	 * 查询通话记录
	 * */
    private class MyAsyncQueryHandler extends AsyncQueryHandler {  
  
        public MyAsyncQueryHandler(ContentResolver cr) {  
            super(cr);  
  
        }  
  
        @Override  
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {   
    		if (cursor == null || cursor.getCount() == 0) {
    			return;
    		} 
    		ArrayList<ContentValues> calllogs = null;
    		while (cursor.moveToNext()) {
    			if (calllogs == null) {
    				calllogs = new ArrayList<ContentValues>(cursor.getCount());
    			}
    			
    			String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
    			String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER)); 
    			int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE)); 
    			String date = cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.DATE));
    			
    			ContentValues calllog = new ContentValues();
    			calllog.put(CallLog.Calls.CACHED_NAME, name);  
    			calllog.put(CallLog.Calls.NUMBER, number); 
    			calllog.put(CallLog.Calls.TYPE, type); 
    			calllog.put(CallLog.Calls.DATE, date);
    			calllogs.add(calllog); 
    		}
    		
    		if (token == TOKEN_ONCREATE) {
    			RecentAdapter adapter = new RecentAdapter(PhoneRecordActivity.this, calllogs);
        		recentList.setAdapter(adapter);
			} else if (token == TOKEN_UPDATE) {
				((RecentAdapter) recentList.getAdapter()).notifyData(calllogs);
			}
    		
    		 
    		if (cursor != null) {
    			cursor.close();
    		}  
        }  
  
    }
}
